package com.rc.saas.tenant.controller.member;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.member.MemberCard;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.member.MemberCardRecordSearch;
import com.rc.saas.tenant.search.member.MemberCardSearch;
import com.rc.saas.tenant.service.member.MemberCardRecordService;
import com.rc.saas.tenant.service.member.MemberCardService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.member.MemberCardRecordResult;
import com.rc.saas.tenant.vo.member.MemberCardResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @author frog
 * @date 2019/11/21
 */
@Controller
@RequestMapping("/memberCard")
public class MemberCardController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(MemberCardController.class);

    @Autowired
    private MemberCardService memberCardService;

    @Autowired
    private MemberCardRecordService memberCardRecordService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private MemberInfoService memberInfoService;

    /**
     * 跳转会员卡页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String memberCardPage() {
        return "/templates/member/memberCard/memberCard";
    }

    /**
     * 返回会员卡列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listMemberCard", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listMemberCard(MemberCardSearch search) {
        PageInfo<MemberCardResult> pageInfo = memberCardService.searchByCondition(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转新增会员卡页面
     *
     * @return
     */
    @RequestMapping(value = "/addMemberCard", method = RequestMethod.GET)
    public String addMemberCard() {
        return "/templates/member/memberCard/addMemberCard";
    }


    /**
     * 生成卡号
     *
     * @return
     */
    @RequestMapping(value = "/generateCardNumber", method = RequestMethod.GET)
    @ResponseBody
    public TResponse generateCardNumber(Integer number) {
        if (number == null) {
            return TResponse.FAIL("请输入正确的参数");
        }
        if (number > 50) {
            return TResponse.FAIL("一次最多生成50条数据");
        }
        //运营商标示+年份+6位流水号 卡号：CWT52019000001
        TenantUser user = ShiroUtils.getSessionUser();
        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantCode());
        String prefix = tenant.getTenantPrefix();

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);

        ArrayList<String> list = new ArrayList<>(number);


        MemberCard memberCard = memberCardService.selectLastCardNo(tenant.getTenantCode());
        //第一次生成卡号
        if (memberCard == null) {
            for (int j = 0; j < number; j++) {
                int i = j + 1;
                String num = String.format("%06d", i);
                list.add(prefix + year + num);
            }

            //持续生成卡号
        } else {

            Integer oldInt = Integer.valueOf(memberCard.getCardNo().substring(8));
            for (int j = 0; j < number; j++) {
                int i = oldInt + j + 1;
                String num = String.format("%06d", i);
                list.add(prefix + year + num);

                if (i > 999999) {
                    return TResponse.FAIL("卡号超过最大值999999");
                }
            }
        }

//        for (int j = 0; j < number; j++) {
//            int i = (int) ((Math.random() * 9 + 1) * 100000);
//            list.add(prefix + year + i);
//        }

        return TResponse.SUCCESS_DATA(list);
    }


    /**
     * 保存会员卡
     *
     * @return
     */
    @RequestMapping(value = "/saveCardNumber", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveCardNumber(MemberCard memberCard) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            String cardNo = memberCard.getCardNo();
            if (cardNo == null) {
                return TResponse.FAIL("请输入正确的参数");
            }
            Date date = new Date();
            MemberCard card = new MemberCard();
            card.setTenantCode(user.getTenantCode());
            card.setCreatedBy(user.getLoginName());
            card.setCreatedTime(date);
            card.setLastUpdatedBy(user.getLoginName());
            card.setLastUpdatedTime(date);
            //状态:0 未绑定 1 已绑定  2已注销 默认0
            card.setOperateStatus("0");
            //设置备注
            card.setRemark(memberCard.getRemark());

            String[] split = memberCard.getCardNo().split(",");
            for (String s : split) {
                card.setCardNo(s);
                memberCardService.insertSelective(card);
            }

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存会员卡失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转绑定/换绑页面
     *
     * @return
     */
    @RequestMapping(value = "/bindAndChange/{cardId}", method = RequestMethod.GET)
    public String bindAndChange(@PathVariable("cardId") Long cardId, Model model) {
        MemberCard card = memberCardService.selectByPrimaryKey(cardId);
        if (card.getMemberId() != null) {
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(card.getMemberId());
            model.addAttribute("memberInfo", memberInfo);
        }
        model.addAttribute("card", card);
        return "/templates/member/memberCard/bindAndChange";
    }


    /**
     * 绑定手机号/解绑/换绑
     *
     * @return
     */
    @RequestMapping(value = "/bindMobile", method = RequestMethod.POST)
    @ResponseBody
    public TResponse bindMobile(Long cardId, String mobile) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            if (StringUtils.isNotEmpty(mobile)) {
                MemberInfo memberInfo = memberInfoService.selectMemberByMobile(user.getTenantCode(), mobile);
                if (memberInfo == null) {
                    return TResponse.FAIL("请输入正确的手机号");
                }
                //    TResponse tResponse = memberCardService.isBindMobile(memberInfo.getMemberId(), user.getTenantCode());
                //    if (tResponse != null) {
                //        return tResponse;
                //    }
                memberCardService.bindMobile(cardId, memberInfo, user);
            } else {
                memberCardService.bindMobile(cardId, null, user);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存电价失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/editMemberCard/{cardId}", method = RequestMethod.GET)
    public String editMemberCard(@PathVariable("cardId") Long cardId, Model model) {
        MemberCard card = memberCardService.selectByPrimaryKey(cardId);
        model.addAttribute("card", card);
        return "/templates/member/memberCard/editMemberCard";
    }


    /**
     * 保存编辑会员卡
     *
     * @return
     */
    @RequestMapping(value = "/saveEditCardNumber", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveEditCardNumber(MemberCard memberCard) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            memberCard.setLastUpdatedBy(user.getLoginName());
            memberCard.setLastUpdatedTime(new Date());
            memberCardService.updateByPrimaryKeySelective(memberCard);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存会员卡失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 注销会员卡
     *
     * @return
     */
    @RequestMapping(value = "/cancelCard", method = RequestMethod.POST)
    @ResponseBody
    public TResponse cancelCard(Long cardId) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            MemberCard card = memberCardService.selectByPrimaryKey(cardId);
            memberCardService.cancelCard(user, card);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("注销失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转历史记录页面
     *
     * @return
     */
    @RequestMapping(value = "/memberCardRecord/{cardId}", method = RequestMethod.GET)
    public String memberCardRecord(@PathVariable("cardId") Long cardId, Model model) {
        model.addAttribute("cardId", cardId);
        return "/templates/member/memberCardRecord/memberCardRecord";
    }


    /**
     * 返回会员卡历史列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listMemberCardRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listMemberCardRecord(MemberCardRecordSearch memberCardRecordSearch) {
        PageInfo<MemberCardRecordResult> pageInfo = memberCardRecordService.searchByCondition(memberCardRecordSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

}
